package cn.juque.datapipeline.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.juque.common.base.PageInfo;
import cn.juque.common.constants.MessageEnum;
import cn.juque.common.exception.AppException;
import cn.juque.datapipeline.entity.TaskScript;
import cn.juque.datapipeline.mapper.TaskScriptMapper;
import cn.juque.datapipeline.service.ITaskScriptService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author JUQUE
 * @version 1.0.0
 * <ul>
 *  <li>simple-generator</li>
 *  <li>脚本信息</li>
 *</ul>
 * {@code @date} 2023-03-31 11:14:13
 **/
@Service("taskScriptService")
public class TaskScriptServiceImpl implements ITaskScriptService {

    @Resource
    private TaskScriptMapper taskScriptMapper;

  /**
   * 分页查询
   *
   * @param pageInfo  pageInfo
   * @param taskScript taskScript
   * @return DataGrid
   */
  @Override
  public List<TaskScript> listScriptWithPage(PageInfo pageInfo, TaskScript taskScript) {
    Page<TaskScript> page = new Page<>(pageInfo.getPage(), pageInfo.getLimit());
    List<TaskScript> list = this.taskScriptMapper.queryScriptList(page, taskScript);
    pageInfo.setTotal(page.getTotal());
    return list;
  }

  /**
   * 查询
   *
   * @param taskScript taskScript
   * @return List
   */
  @Override
  public List<TaskScript> listScriptWithoutPage(TaskScript taskScript) {
    return this.taskScriptMapper.queryScriptList(taskScript);
  }

      /**
       * 详情
       *
       * @param id 主键
       * @return TaskScript
       */
      @Override
      public TaskScript detail(String id) {
          return this.taskScriptMapper.selectById(id);
      }

  /**
   * 保存
   *
   * @param taskScript taskScript
   */
  @Override
  public void saveScript(TaskScript taskScript) {
    boolean flag = SqlHelper.retBool(this.taskScriptMapper.insert(taskScript));
    if (!flag) {
      throw new AppException(MessageEnum.SAVE_FAIL);
    }
  }

  /**
   * 更新
   *
   * @param taskScript taskScript
   */
  @Override
  public void updateScript(TaskScript taskScript) {
    boolean flag = SqlHelper.retBool(this.taskScriptMapper.updateById(taskScript));
    if (!flag) {
      throw new AppException(MessageEnum.UPDATE_FAIL);
    }
  }

  /**
   * 删除
   *
   * @param ids 主键列表
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteScript(List<String> ids) {
    if (CollUtil.isEmpty(ids)) {
      return ;
    }
   int count = this.taskScriptMapper.deleteBatchIds(ids);
    if(count != ids.size()){
        throw new AppException(MessageEnum.DELETE_FAIL);
    }
  }

}
